import React 				from 'react';
import { Link }				from 'react-router-dom';
import PageTitle    		from 'component/pagetitle/index.jsx';
import MUtil        		from 'util/mm.jsx'
import Product         		from 'service/product-service.jsx'
import TableView			from 'component/tableview/index.jsx';

const _util = new MUtil();
const _product = new Product();
class CategoryList extends React.Component{
	
	constructor(props){
		super(props);
		this.state = {
			 list     				: [],
			 parentCategoryId		: this.props.match.params.categoryId || 0
		}
	}
	
	componentDidMount(){
		this.loadCategoryList();
	}
	
	componentDidUpdate(prevProps,prevState){
		const prevPath = prevProps.location.pathname,
			  newPath  = this.props.location.pathname,
			  newId	   = this.props.match.params.categoryId || 0;
		if (prevPath != newPath) {
			this.setState({parentCategoryId:newId},() =>{
				this.loadCategoryList();
			})
		}
	}
	
	loadCategoryList(){
		console.log(this.state.parentCategoryId);
		_product.getCategoryList(this.state.parentCategoryId)
			.then(res => {
				this.setState({list:res});
			},err =>{
				this.setState({list:[]});
				_util.errorTips(err);
			})
	}
	
	onUpdateCategoryName(id,name){
		let newName = window.prompt('请输入新的品类名称',name);
		console.log(newName);
		if (newName) {
			_product.updateCategoryName(id,newName)
					.then(res => {
						_util.successTips(res);
						this.loadCategoryList();
					},errMsg =>{
						_util.errorTips(errMsg);
					})
		}
	}
	
	
	render(){
		const tbodyList = this.state.list.map((category,index) => {
			return (
				<tr key={index}>
					<td>{category.id}</td>
					<td>{category.name}</td>
					<td className="text-center">
						<a 	className='opear' onClick={(e) => {this.onUpdateCategoryName(category.id,category.name)}}>修改名称</a>
						{	category.parentId === 0 
							? <Link className='opear' to={`/product-category/index/${category.id}`}>查看子品类</Link>
							: null
						}
					</td>
				</tr>
			)
		})
		
		return (
			<div id="page-wrapper">
				<PageTitle title='品类管理' />
				<div className="page-header-right">
					<Link className="btn btn-primary" to="/product-category/add">
						<i className="fa fa-plus"></i>
						<span>添加品类</span>
					</Link>
				</div>
				<p>当前商品分类ID：{this.state.parentCategoryId}</p>
				<TableView theaders={['品类Id','品类名称','操作']} >
					{tbodyList}
				</TableView>
			</div>
		)
	}
}

export default CategoryList;